﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using System.Threading;

public partial class BookingNote_BookingNoteEdit : BasePage
{
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    ISyMarketHandler markManage = new SyMarketHandler();
    ISyPlaceHandler placeManage = new SyPlaceHandler();
    ISyDestinationHandler destManage = new SyDestinationHandler();
    IBNBookingNoteHandler bookingNoteManage = new BNBookingNoteHandler();
    private static string clientName = string.Empty;
    private static int num = -1;
    DataBase db = new DataBase();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1054")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
            }
//            txtBespokeDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

            btnDelD.Attributes.Add("OnClick", "javascript:return confirm('" + Resources.Messages.DelRecord + "');");
            ddlShipper.Focus();
            ViewState["OrderBy"] = "RowNum";
            ViewState["Accending"] = "asc";
            FillDDl();
           
            dataBind();
        }
    }

    #region dataBind
    private void dataBind()
    {

        DataTable dt = new DataTable();
        if (ViewState["BookingNote"] != null)
        {
            divEntrust.Visible = true;
            dt = (DataTable)ViewState["BookingNote"];

            DataView view = dt.DefaultView;
            view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
            gvBookNoteDetailList.DataSource = view;
            gvBookNoteDetailList.DataBind();
            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = dt.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }

        }
        else
        {
            divEntrust.Visible = false;
        }
    }

    #endregion

    #region FillDDl
    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        ddlShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlShipper.DataTextField = "HKShortName";
        }
        else
        {
            ddlShipper.DataTextField = "CNShortName";
        }
        ddlShipper.DataValueField = "PKID";
        ddlShipper.DataBind();
        ddlShipper.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //客户客人
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.KHKR.ToString("d")));
        ddlCustomer.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCustomer.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCustomer.DataTextField = "HKShortName";
        }
        else
        {
            ddlCustomer.DataTextField = "CNShortName";
        }
        ddlCustomer.DataValueField = "PKID";
        ddlCustomer.DataBind();
        ddlCustomer.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //市场
        dt = markManage.GetList();
        ddlMarket.DataSource = dt;
        ddlMarket.DataTextField = "CNName";
        ddlMarket.DataValueField = "PKID";
        ddlMarket.DataBind();
        ddlMarket.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //目的地
        dt = destManage.GetList();
        ddlDestination.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlDestination.DataTextField = "ENGName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlDestination.DataTextField = "HKName";
        }
        else
        {
            ddlDestination.DataTextField = "CNName";
        }
        ddlDestination.DataValueField = "PKID";
        ddlDestination.DataBind();
        ddlDestination.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));


        //工厂
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        //ddlVendor.DataSource = dt;
        //if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        //{
        //    ddlVendor.DataTextField = "ENGShortName";
        //}
        ddlVendor.Items.Add(new ListItem(Resources.Messages.PleaseSelect, "0"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem item = new ListItem();
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                // ddlVendor.DataTextField = "HKShortName";
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["HKShortName"].ToString();
            }
            else
            {
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["CNShortName"].ToString();
                //ddlVendor.DataTextField = "CNShortName";
            }
            item.Value = dt.Rows[i]["PKID"].ToString();
           // ddlVendor.DataValueField = "PKID";
            ddlVendor.Items.Add(item);
        }
       // ddlVendor.DataBind();
       // ddlVendor.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //仓库
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.CK.ToString("d")));
        ddlWhouse.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlWhouse.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlWhouse.DataTextField = "HKShortName";
        }
        else
        {
            ddlWhouse.DataTextField = "CNShortName";
        }
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));


        //船公司/货代
        SqlParameter[] parms = new SqlParameter[3];
        parms[0] = new SqlParameter("@TypeID", Enums.CT.CGS.ToString("d"));
        parms[1] = new SqlParameter("@Status", "1");
        parms[2] = new SqlParameter("@TypeID2", Enums.CT.HD.ToString("d"));
        string sqlStr = "select * from Sy_Client where PKID in(select ClientID from Sy_ClientType where SyCodeID=@TypeID OR SyCodeID=@TypeID2) and Status=@Status";

        dt = clientManage.GetClientList(sqlStr, parms);
        ddlCarrierForwar.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCarrierForwar.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCarrierForwar.DataTextField = "HKShortName";
        }
        else
        {
            ddlCarrierForwar.DataTextField = "CNShortName";
        }
        ddlCarrierForwar.DataValueField = "PKID";
        ddlCarrierForwar.DataBind();
        ddlCarrierForwar.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }
    #endregion


    #region gv方法

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvBookNoteDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvBookNoteDetailList.PageCount)
            {
                this.gvBookNoteDetailList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvBookNoteDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }

    protected void gvBookNoteDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvBookNoteDetailList.PageIndex = e.NewPageIndex;
        dataBind();
    }
   
    protected void gvBookNoteDetailList_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }
    #endregion


    #region 添加数据到缓存

    protected void btnSub_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        string vendorName = string.Empty;
        string whouseName = string.Empty;
        string placeName = string.Empty;
        string vendorLinkManName = string.Empty;
        if (ddlVendor.SelectedValue != "0")
        {
            vendorName = ddlVendor.SelectedItem.Text;
        }
        if (ddlWhouse.SelectedValue != "0")
        {
            whouseName = ddlWhouse.SelectedItem.Text;
        }
        if (ddlVendorLM.SelectedValue != "0" && ddlVendorLM.SelectedValue !=string.Empty)
        {
            vendorLinkManName = ddlVendorLM.SelectedItem.Text;
        }
    
        if (ViewState["BookingNote"] == null)//新建第一条数据
        {
            dt.Columns.Add("RowNum");
            dt.Columns.Add("ConfirmNO");
            dt.Columns.Add("VendorID");
            dt.Columns.Add("WhouseID");
            dt.Columns.Add("PlaceID");
            dt.Columns.Add("SONO");
            dt.Columns.Add("FCLLCL");
            dt.Columns.Add("HKPRC");
            dt.Columns.Add("JobDate");
            dt.Columns.Add("DeliveryDate");
            dt.Columns.Add("ItemNO");
            dt.Columns.Add("PCS");
            dt.Columns.Add("CTN");
            dt.Columns.Add("GrossWT");
            dt.Columns.Add("VOL");
            dt.Columns.Add("ContainerNO");
            dt.Columns.Add("SealNO");
            dt.Columns.Add("VV");
            dt.Columns.Add("PNNO");
            dt.Columns.Add("BuyerPONO");
            dt.Columns.Add("PCNO");
            dt.Columns.Add("CargoReadyDate");
            dt.Columns.Add("TruckCO");
            dt.Columns.Add("Remark");
            dt.Columns.Add("VendorName");
            dt.Columns.Add("WhouseName");
            dt.Columns.Add("PlaceName");
            dt.Columns.Add("BespokeDate");
            dt.Columns.Add("VendorLinkMan");
            dt.Columns.Add("VendorLinkManName");
            dt.Columns.Add("SourceCode");

            dt.Rows.Add(new string[] {
                "1",
                txtConfirmNo.Text.Trim(),
                ddlVendor.SelectedValue,
                ddlWhouse.SelectedValue,
                "0",
                txtSONO.Text.Trim(),               
                ddlFCLLCL.SelectedValue,
                ddlHKPRC.SelectedValue,
                txtJobDate.Text!=string.Empty?txtJobDate.Text.Trim() +HK2009.Common.StringUtil.GetTime(txtJobDateH.Text.Trim()):string.Empty,
                 System.DBNull.Value.ToString(),
                txtItemNO.Text.Trim(),
                txtPCS.Text.Trim() !=string.Empty?txtPCS.Text.Trim():"0",
                txtCTN.Text.Trim()!=string.Empty?txtCTN.Text.Trim():"0",
                txtGrossWT.Text.Trim()!=string.Empty ?txtGrossWT.Text.Trim():"0",
                txtVOL.Text.Trim() !=string.Empty ? txtVOL.Text.Trim() :"0",
                txtContainerNO.Text.Trim(),
                txtSealNO.Text.Trim(),
                string.Empty,
                txtPNNO.Text.Trim(),
                string.Empty,
                txtPCNOD.Text.Trim(),
                txtCargoReadyDate.Text.Trim(),
                string.Empty,
                txtRemarkD.Text.Trim(),
                vendorName,
                whouseName,
                placeName,
               System.DBNull.Value.ToString() ,
                ddlVendorLM.SelectedValue != string.Empty ?ddlVendorLM.SelectedValue:"0" ,
                vendorLinkManName,
                string.Empty
            });
        }
        else if (num != -1)//更新缓存的其中一条数据
        {
            dt = (DataTable)ViewState["BookingNote"];
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    if (i != num - 1)
            //    {
            //        if (dt.Rows[i]["SONO"].ToString() == txtSONO.Text.Trim() && dt.Rows[i]["ItemNo"].ToString()==txtItemNO.Text.Trim())
            //        {
            //            Jscript.Alert("已存在SONO为" + txtSONO.Text.Trim() + "和ItemNO为" + txtItemNO.Text.Trim() + "的记录!");
            //            return;
            //        }
            //    }
            //}

            dt.Rows[(num - 1)]["ConfirmNo"] = txtConfirmNo.Text;
            dt.Rows[(num - 1)]["VendorID"] = ddlVendor.SelectedValue;
            dt.Rows[(num - 1)]["WhouseID"] = ddlWhouse.SelectedValue;
            dt.Rows[(num - 1)]["PlaceID"] = "0";
            dt.Rows[(num - 1)]["SONO"] = txtSONO.Text;
            dt.Rows[(num - 1)]["FCLLCL"] = ddlFCLLCL.SelectedValue;
            dt.Rows[(num - 1)]["HKPRC"] = ddlHKPRC.SelectedValue;
            dt.Rows[(num - 1)]["JobDate"] = txtJobDate.Text != string.Empty ?txtJobDate.Text.Trim() +HK2009.Common.StringUtil.GetTime(txtJobDateH.Text.Trim()): string.Empty;

            dt.Rows[(num - 1)]["DeliveryDate"] = System.DBNull.Value.ToString();
            dt.Rows[(num - 1)]["ItemNO"] = txtItemNO.Text;
            dt.Rows[(num - 1)]["PCS"] = txtPCS.Text !=string.Empty ?txtPCS.Text.Trim():"0";
            dt.Rows[(num - 1)]["CTN"] = txtCTN.Text != string.Empty ? txtCTN.Text.Trim() : "0";
            dt.Rows[(num - 1)]["GrossWT"] = txtGrossWT.Text != string.Empty ? txtGrossWT.Text.Trim() : "0";
            dt.Rows[(num - 1)]["VOL"] = txtVOL.Text != string.Empty ? txtVOL.Text.Trim() : "0";
            dt.Rows[(num - 1)]["ContainerNO"] = txtContainerNO.Text;
            dt.Rows[(num - 1)]["SealNO"] = txtSealNO.Text;
            dt.Rows[(num - 1)]["VV"] = txtVVD.Text;
            dt.Rows[(num - 1)]["PNNO"] = txtPNNO.Text;
            dt.Rows[(num - 1)]["BuyerPONO"] = string.Empty;
            dt.Rows[(num - 1)]["PCNO"] = txtPCNOD.Text;
            dt.Rows[(num - 1)]["CargoReadyDate"] = txtCargoReadyDate.Text;
            dt.Rows[(num - 1)]["TruckCO"] = string.Empty;
            dt.Rows[(num - 1)]["Remark"] = txtRemarkD.Text;
            dt.Rows[(num - 1)]["VendorName"] = vendorName;
            dt.Rows[(num - 1)]["WhouseName"] = whouseName;
            dt.Rows[(num - 1)]["PlaceName"] = placeName;
            dt.Rows[(num - 1)]["BespokeDate"] = System.DBNull.Value.ToString();
            dt.Rows[(num - 1)]["VendorLinkMan"] = ddlVendorLM.SelectedValue != string.Empty ? ddlVendorLM.SelectedValue : "0";
            dt.Rows[(num - 1)]["VendorLinkManName"] = vendorLinkManName;
            dt.Rows[(num - 1)]["SourceCode"] = string.Empty;
        }
        else//添加第二条以上数据
        {
            dt = (DataTable)ViewState["BookingNote"];

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    if (dt.Rows[i]["SONO"].ToString() == txtSONO.Text.Trim() && dt.Rows[i]["ItemNo"].ToString()==txtItemNO.Text.Trim())
            //    {
            //        Jscript.Alert("已存在SONO为" + txtSONO.Text.Trim() + "和ItemNO为" + txtItemNO.Text.Trim() + "的记录!");
            //        return;
            //    }
            //}

            dt.Rows.Add(new string[] {
                Convert.ToString(dt.Rows.Count+1),
                txtConfirmNo.Text.Trim(),
                ddlVendor.SelectedValue,
                ddlWhouse.SelectedValue,
                "0",
                txtSONO.Text.Trim(),
                ddlFCLLCL.SelectedValue,
                ddlHKPRC.SelectedValue,
                txtJobDate.Text!=string.Empty?txtJobDate.Text.Trim() +HK2009.Common.StringUtil.GetTime(txtJobDateH.Text.Trim()):string.Empty,

                System.DBNull.Value.ToString(),
                txtItemNO.Text.Trim(),
                txtPCS.Text.Trim() !=string.Empty?txtPCS.Text.Trim():"0",
                txtCTN.Text.Trim()!=string.Empty?txtCTN.Text.Trim():"0",
                txtGrossWT.Text.Trim()!=string.Empty ?txtGrossWT.Text.Trim():"0",
                txtVOL.Text.Trim() !=string.Empty ? txtVOL.Text.Trim() :"0",
                txtContainerNO.Text.Trim(),
                txtSealNO.Text.Trim(),
                string.Empty,
                txtPNNO.Text.Trim(),
                string.Empty,
                txtPCNOD.Text.Trim(),
                txtCargoReadyDate.Text.Trim(),
                string.Empty,
                txtRemarkD.Text.Trim(),
                vendorName,
                whouseName,
                placeName,
                System.DBNull.Value.ToString(),
                 ddlVendorLM.SelectedValue != string.Empty ?ddlVendorLM.SelectedValue:"0" ,
                vendorLinkManName,
                string.Empty
            });
        }

        ViewState["BookingNote"] = dt;
        dataBind();
        ClearSelect();
        // CloseSelect();

    }

    #endregion

    #region ClearSelect
    /// <summary>
    ///
    /// </summary>
    private void CloseSelect()
    {

    }

    private void ClearSelect()
    {
        txtConfirmNo.Text = string.Empty;
        ddlVendor.SelectedValue = "0";
        ddlWhouse.SelectedValue = "0";
        //ddlPlace.SelectedValue = "0";
        txtSONO.Text = string.Empty;
        ddlFCLLCL.SelectedValue = "FCL";
        ddlHKPRC.SelectedValue = "HK";
        txtJobDate.Text = string.Empty;
      //  txtDeliveryDate.Text = string.Empty;
        txtItemNO.Text = string.Empty;
        txtPCS.Text = string.Empty;
        txtCTN.Text = string.Empty;
        txtGrossWT.Text = string.Empty;
        txtVOL.Text = string.Empty;
        txtContainerNO.Text = string.Empty;
        txtSealNO.Text = string.Empty;
        //txtVVD.Text = string.Empty;
        txtPNNO.Text = string.Empty;
        //txtBuyerPONO.Text = string.Empty;
        txtPCNOD.Text = string.Empty;
        txtCargoReadyDate.Text = string.Empty;
        //txtTruckCO.Text = string.Empty;
        txtRemarkD.Text = string.Empty;
       // txtBespokeDate.Text = string.Empty;
        txtJobDateH.Text = string.Empty;

        ddlVendorLM.Items.Clear();
        ddlVendorLM.DataBind();
        ddlVendorLM.Enabled = false;
        num = -1;
       // txtSourceCode.Text = string.Empty;
    }

    #endregion

    protected void btnClose_Click(object sender, EventArgs e)
    {
        ClearSelect();
    }

    #region 添加托运单
    protected void btnAdd_Click(object sender, EventArgs e)
    {

        string sqlBooking = string.Empty;
        string sqlBookingDtl = string.Empty;
        SqlParameter[] parms = null;
        List<SqlParameter> list = new List<SqlParameter>();

        string templete = string.Empty;
        string emailTo = string.Empty;


        string sqlStr = @"INSERT INTO BN_BookingNote(PoNO,ShipperID,ShipperLMID,InvoiceNO,PcNO,WinStart,WinClose,WinLastClose,CustomerID,MarketID,
                        DestinationID,CarrierForwar,CreatedDate,CreatedUser,Status,VV,SICutOFFDate,BillDate,CPO,Remark,JobNumber,SourceCode) VALUES(dbo.Fn_NextBookingNoteNO(),@ShipperID,@ShipperLMID,
                        @InvoiceNO,@PcNO,@WinStart,@WinClose,@WinLastClose,@CustomerID,@MarketID,
                        @DestinationID,@CarrierForwar,@CreatedDate,@CreatedUser,@Status,@VV,@SICutOFFDate,@BillDate,@CPO,@Remark,@JobNumber,@SourceCode) SET @ReturnValue=@@Identity;";
        if (ViewState["BookingNote"] != null)
        {
            DataTable dt = (DataTable)ViewState["BookingNote"];
            string vendorID = string.Empty;
            int ii = 0;


            if (dt != null && dt.Rows.Count > 0)
            {
                DataView view = dt.DefaultView;
                view.Sort = "VendorID asc";

                for (int i = 0; i < view.Count; i++)
                {

                    list.Add(new SqlParameter("@ConfirmNO" + i.ToString(), view[i]["ConfirmNO"].ToString()));
                    list.Add(new SqlParameter("@VendorID" + i.ToString(), view[i]["VendorID"].ToString()));
                    list.Add(new SqlParameter("@WhouseID" + i.ToString(), view[i]["WhouseID"].ToString()));
                    list.Add(new SqlParameter("@PlaceID" + i.ToString(), view[i]["PlaceID"].ToString()));

                    list.Add(new SqlParameter("@SONO" + i.ToString(), view[i]["SONO"].ToString()));
                    list.Add(new SqlParameter("@FCLLCL" + i.ToString(), view[i]["FCLLCL"].ToString()));
                    list.Add(new SqlParameter("@HKPRC" + i.ToString(), view[i]["HKPRC"].ToString()));

                    list.Add(new SqlParameter("@StatusDtl" + i.ToString(), Enums.BookingNoteDtlStatus.BOOKING.ToString("d")));
                    list.Add(new SqlParameter("@BookingDate" + i.ToString(), DateTime.Now));

                    int userID = 0;
                    string sqlUser = "select UserID from Users where LoginID='" + view[i]["VendorLinkManName"] + "'";
                    DataTable dtuser = db.RunSql(sqlUser);
                    if (dtuser != null && dtuser.Rows.Count > 0)
                    {
                        int.TryParse(dtuser.Rows[0]["UserID"].ToString(), out userID);
                    }


                    list.Add(new SqlParameter("@BookingUser" + i.ToString(), Session["UserID"].ToString()));//userID

                    if (view[i]["JobDate"].ToString() == string.Empty)
                    {
                        list.Add(new SqlParameter("@JobDate" + i.ToString(), System.DBNull.Value));
                       // list.Add(new SqlParameter("@StatusDtl" + i.ToString(), Enums.BookingNoteDtlStatus.NEW.ToString("d")));
                      //  list.Add(new SqlParameter("@BookingDate" + i.ToString(), System.DBNull.Value));
                        //list.Add(new SqlParameter("@BookingUser" + i.ToString(), System.DBNull.Value));
                    }
                    //添加到booking相关表
                    else
                    {
                        list.Add(new SqlParameter("@JobDate" + i.ToString(), view[i]["JobDate"].ToString()));
                       

                        //                        if (vendorID.Contains(view[i]["VendorID"].ToString()))
                        //                        {
                        //                            sqlBookingDtl += @"INSERT INTO BN_BookingDtl(BookingID,BookingNoteDtlID,ShipperID,SONO,PNNO,WinStart,
                        //                                            WinClose, JobDate,DeliveryDate,WhouseID,FCLLCL,ItemNO,PCS,CTN,GrossWT,VOL,Remark,ShipperID,PlaceID)
                        //                                            VALUES(@BookingIDReturn" + ii.ToString() + ",@BookingDtlReturn" + i.ToString() + ",@ShipperID,@SONO" + i.ToString()
                        //                                            + ",@PNNO" + i.ToString() + ",@WinStart,@WinClose,@JobDate" + i.ToString() + ",@DeliveryDate" + i.ToString()
                        //                                            + ",@WhouseID" + i.ToString() + ",@FCLLCL" + i.ToString() + ",@ItemNO" + i.ToString()
                        //                                            + ",@PCS" + i.ToString() + ",@CTN" + i.ToString() + ",@GrossWT" + i.ToString() + ",@VOL" + i.ToString()
                        //                                            + ",@Remark2" + i.ToString() +",@PlaceID" + i.ToString() + ");";
                        //                        }
                        //else
                        //{



                        //}

                        // vendorID += view[i]["VendorID"].ToString() + ",";

                        List<string> emailList = new List<string>();
                        string sqlStrSelect = string.Empty;

                        // 读取托运人的联络人email
                        //                        sqlStrSelect = @"SELECT * 
                        //                            FROM Sy_ClientLinkMan where PKID=@PKID";
                        DataTable dtEmail;

                        SqlParameter[] parmsSelect = null;

                        //parmsSelect = new SqlParameter[1];
                        //parmsSelect[0] = new SqlParameter("@PKID", ddlShipperLM.SelectedValue);
                        //dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                        //if (dtEmail != null && dtEmail.Rows.Count > 0)
                        //{
                        //    foreach (DataRow row in dtEmail.Rows)
                        //    {
                        //        emailList.Add(row["Email"].ToString());
                        //    }
                        //}

                        // 读取工厂的联络人email
                        sqlStrSelect = @"SELECT * 
                            FROM Sy_ClientLinkMan where PKID=@PKID";

                        parmsSelect = new SqlParameter[1];
                        parmsSelect[0] = new SqlParameter("@PKID", view[i]["VendorLinkMan"].ToString());
                        dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                        {
                            foreach (DataRow row in dtEmail.Rows)
                            {
                                emailList.Add(row["Email"].ToString());
                            }
                        }


//                        // 读取公司联系人email
//                      string sqlStrComp = @"SELECT users.*
//                               FROM Users users INNER JOIN
//                                    Sy_Client ON users.UserID = Sy_Client.CompanyBP
//                               WHERE Sy_Client.PKID = @VendorID";
//                      SqlParameter[] parmsComp = new SqlParameter[1];
//                      parmsComp[0] = new SqlParameter("@VendorID", view[i]["VendorID"].ToString());
//                      dtEmail = db.RunSqlTab(sqlStrComp, parmsComp);
//                        if (dtEmail != null && dtEmail.Rows.Count > 0)
//                        {
//                            foreach (DataRow row in dtEmail.Rows)
//                            {
//                                emailList.Add(row["Email"].ToString());
//                            }
//                        }

                        // 读取自己的email
                        string sqlStrComp = "SELECT * FROM Users WHERE UserID = @UserID";
                       SqlParameter[] parmsMy = new SqlParameter[1];
                       parmsMy[0] = new SqlParameter("@UserID", Session["UserID"].ToString());
                       dtEmail = db.RunSqlTab(sqlStrComp, parmsMy);
                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                        {
                            foreach (DataRow row in dtEmail.Rows)
                            {
                                emailList.Add(row["Email"].ToString());
                            }
                        }


                        //发email模板
                        templete += @"


[list]




                               ";
                        string dateFormat = "yyyy-MM-dd HH:mm:ss";
                        string change = string.Empty;

                        change = change + "ItemNO:" + view[i]["ItemNO"].ToString() + @"

";
                        change = change + "SONO:" + view[i]["SONO"].ToString() + @"

";
                        change = change + "PNNO:" + view[i]["PNNO"].ToString() + @"

";
                        change = change + "Added by:" + Session["LoginID"].ToString() + @"

";

                        change += "Added JobDate to:" + DateTime.Parse(view[i]["JobDate"].ToString()).ToString(dateFormat) + @"
";



                        templete = templete.Replace("[list]", change);


                        foreach (string email in emailList)
                        {
                            if (StringUtil.IsEmailAddress(email))
                            {
                                //templete = templete.Replace("[title]", email);
                                emailTo += email + ",";
                            }
                        }
                        if (emailTo != string.Empty)
                        {
                            emailTo = emailTo.Substring(0, emailTo.Length - 1) + ";";
                        }
                        templete += "}";
                    }

                    ii += 1;

                    SqlParameter parmBID = new SqlParameter("@BookingIDReturn" + ii.ToString(), 0);
                    parmBID.Direction = ParameterDirection.Output;
                    parmBID.SqlDbType = SqlDbType.Int;
                    list.Add(parmBID);

                    sqlBooking += @"INSERT INTO BN_Booking(BookingNO,Status,VendorID,BookingUser,BookingDate)
                                         VALUES(dbo.Fn_NextBookingNO(), @StatusBooking, @VendorID" + i.ToString() + ", @BookingUser" + i.ToString() + ", GETDATE()) SET @BookingIDReturn" + ii.ToString() + "=@@Identity; ";

                    sqlBookingDtl += @"INSERT INTO BN_BookingDtl(BookingID,BookingNoteDtlID,ShipperID,SONO,PNNO,WinStart,
                                            WinClose, JobDate,DeliveryDate,WhouseID,FCLLCL,ItemNO,PCS,CTN,GrossWT,VOL,Remark,PlaceID)
                                            VALUES(@BookingIDReturn" + ii.ToString() + ",@BookingDtlReturn" + i.ToString() + ",@ShipperID,@SONO" + i.ToString()
                                         + ",@PNNO" + i.ToString() + ",@WinStart,@WinClose,@JobDate" + i.ToString() + ",@DeliveryDate" + i.ToString()
                                         + ",@WhouseID" + i.ToString() + ",@FCLLCL" + i.ToString() + ",@ItemNO" + i.ToString()
                                         + ",@PCS" + i.ToString() + ",@CTN" + i.ToString() + ",@GrossWT" + i.ToString() + ",@VOL" + i.ToString()
                                         + ",@Remark2" + i.ToString() + ",@PlaceID" + i.ToString() + ");";



                    if (view[i]["DeliveryDate"].ToString() == string.Empty)
                    {
                        list.Add(new SqlParameter("@DeliveryDate" + i.ToString(), System.DBNull.Value));
                    }
                    else
                    {
                        list.Add(new SqlParameter("@DeliveryDate" + i.ToString(), view[i]["DeliveryDate"].ToString()));
                    }

                    list.Add(new SqlParameter("@ItemNO" + i.ToString(), view[i]["ItemNO"].ToString()));
                    list.Add(new SqlParameter("@PCS" + i.ToString(), view[i]["PCS"].ToString()));
                    list.Add(new SqlParameter("@CTN" + i.ToString(), view[i]["CTN"].ToString()));

                    list.Add(new SqlParameter("@GrossWT" + i.ToString(), view[i]["GrossWT"].ToString()));
                    list.Add(new SqlParameter("@VOL" + i.ToString(), view[i]["VOL"].ToString()));
                    list.Add(new SqlParameter("@ContainerNO" + i.ToString(), view[i]["ContainerNO"].ToString()));
                    list.Add(new SqlParameter("@SealNO" + i.ToString(), view[i]["SealNO"].ToString()));
                    list.Add(new SqlParameter("@VV2" + i.ToString(), view[i]["VV"].ToString()));

                    list.Add(new SqlParameter("@PNNO" + i.ToString(), view[i]["PNNO"].ToString()));
                    list.Add(new SqlParameter("@BuyerPONO" + i.ToString(), view[i]["BuyerPONO"].ToString()));
                    list.Add(new SqlParameter("@PCNO" + i.ToString(), view[i]["PCNO"].ToString()));
                    list.Add(new SqlParameter("@VendorLinkMan" + i.ToString(), view[i]["VendorLinkMan"].ToString()));

                    SqlParameter parmBDtl = new SqlParameter("@BookingDtlReturn" + i.ToString(), 0);
                    parmBDtl.SqlDbType = SqlDbType.Int;
                    parmBDtl.Direction = ParameterDirection.Output;
                    list.Add(parmBDtl);


                    if (view[i]["CargoReadyDate"].ToString() == string.Empty)
                    {
                        list.Add(new SqlParameter("@CargoReadyDate" + i.ToString(), System.DBNull.Value));
                    }
                    else
                    {
                        list.Add(new SqlParameter("@CargoReadyDate" + i.ToString(), view[i]["CargoReadyDate"].ToString()));
                    }

                    list.Add(new SqlParameter("@TruckCO" + i.ToString(), view[i]["TruckCO"].ToString()));
                    list.Add(new SqlParameter("@Remark2" + i.ToString(), view[i]["Remark"].ToString()));

                    if (view[i]["BespokeDate"].ToString() == string.Empty)
                    {
                        list.Add(new SqlParameter("@BespokeDate" + i.ToString(), System.DBNull.Value));
                    }
                    else
                    {
                        list.Add(new SqlParameter("@BespokeDate" + i.ToString(), view[i]["BespokeDate"].ToString()));
                    }

                    list.Add(new SqlParameter("@SourceCode" + i.ToString(), view[i]["SourceCode"].ToString()));


                    sqlStr += @"INSERT INTO BN_BookingNoteDtl(BookingNoteID,ConfirmNO,VendorID,WhouseID,PlaceID,SONO,FCLLCL,HKPRC,JobDate,DeliveryDate,
                               ItemNO,PCS,CTN,GrossWT,VOL,ContainerNO,SealNO,VV,CreatedDate,CreatedUser,Status,PNNO,BuyerPONO,PCNO,CargoReadyDate,TruckCO,Remark,BespokeDate,VendorLinkMan,BookingDate,BookingUser,SourceCode)
                               VALUES(@ReturnValue,@ConfirmNO" + i.ToString() + ",@VendorID" + i.ToString() + ",@WhouseID" + i.ToString() + ",@PlaceID" + i.ToString() + ",";

                    sqlStr += "@SONO" + i.ToString() + ",@FCLLCL" + i.ToString() + ",@HKPRC" + i.ToString() + ",@JobDate" + i.ToString() + ",@DeliveryDate" + i.ToString() + ",";
                    sqlStr += "@ItemNO" + i.ToString() + ",@PCS" + i.ToString() + ",@CTN" + i.ToString() + ",@GrossWT" + i.ToString() + ",@VOL" + i.ToString() + ",";
                    sqlStr += "@ContainerNO" + i.ToString() + ",@SealNO" + i.ToString() + ",@VV2" + i.ToString() + ",@CreatedDate,@CreatedUser,@StatusDtl" + i.ToString() + ",@PNNO" + i.ToString() + ",";
                    sqlStr += "@BuyerPONO" + i.ToString() + ",@PCNO" + i.ToString() + ",@CargoReadyDate" + i.ToString() + ",@TruckCO" + i.ToString() + ",@Remark2" + i.ToString() + ",@BespokeDate" + i.ToString() + ",@VendorLinkMan" + i.ToString() + ",@BookingDate" + i.ToString() + ",@BookingUser" +i.ToString() +  ",@SourceCode" + i.ToString() + ") SET @BookingDtlReturn" + i.ToString() + "=@@Identity;";
                }
            }
        }

        SqlParameter parm = new SqlParameter("@ReturnValue", 0);
        parm.SqlDbType = SqlDbType.Int;
        parm.Direction = ParameterDirection.Output;

        list.Add(parm);
        list.Add(new SqlParameter("@ShipperID", ddlShipper.SelectedValue));
        list.Add(new SqlParameter("@ShipperLMID", ddlShipperLM.SelectedValue));
        list.Add(new SqlParameter("@InvoiceNO", txtInvoiceNO.Text.Trim()));
        list.Add(new SqlParameter("@PcNO", txtPcNO.Text.Trim()));


        if (txtWinStart.Text == string.Empty)
        {
            list.Add(new SqlParameter("@WinStart", System.DBNull.Value));
        }
        else
        {
            list.Add(new SqlParameter("@WinStart", txtWinStart.Text));
        }

        if (txtWinClose.Text == string.Empty)
        {
            list.Add(new SqlParameter("@WinClose", System.DBNull.Value));
        }
        else
        {
            list.Add(new SqlParameter("@WinClose", txtWinClose.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtWinCloseH.Text.Trim())));
        }

        if (txtWinLastClose.Text == string.Empty)
        {
            list.Add(new SqlParameter("@WinLastClose", System.DBNull.Value));
        }
        else
        {
            list.Add(new SqlParameter("@WinLastClose", txtWinLastClose.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtWinLastCloseH.Text.Trim())));
        }

        list.Add(new SqlParameter("@CustomerID", ddlCustomer.SelectedValue));
        list.Add(new SqlParameter("@MarketID", ddlMarket.SelectedValue));
        list.Add(new SqlParameter("@DestinationID", ddlDestination.SelectedValue));
        list.Add(new SqlParameter("@CarrierForwar", ddlCarrierForwar.SelectedValue));
        list.Add(new SqlParameter("@CreatedDate", DateTime.Now));
        list.Add(new SqlParameter("@CreatedUser", Session["UserID"].ToString()));

        list.Add(new SqlParameter("@Status", Enums.BookingNoteStatus.CHECK.ToString("d")));
        list.Add(new SqlParameter("@VV", txtVVD.Text.Trim()));

        list.Add(new SqlParameter("@StatusBooking", Enums.BookingStatus.NEW.ToString("d")));

     
        if (txtSICutOFFDate.Text == string.Empty)
        {
            list.Add(new SqlParameter("@SICutOFFDate", System.DBNull.Value));
        }
        else
        {
            list.Add(new SqlParameter("@SICutOFFDate", txtSICutOFFDate.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtSICutOFFDateH.Text.Trim())));
        }


        if (txtBillDate.Text == string.Empty)
        {
            list.Add(new SqlParameter("@BillDate", System.DBNull.Value));
        }
        else
        {
            list.Add(new SqlParameter("@BillDate", txtBillDate.Text));
        }
        list.Add(new SqlParameter("@CPO", txtCPO.Text.Trim()));
        list.Add(new SqlParameter("@Remark", txtRemark.Text.Trim()));
        list.Add(new SqlParameter("@JobNumber",txtJobNum.Text.Trim()));

        list.Add(new SqlParameter("@SourceCode",txtSourceCode.Text.Trim()));

        parms = list.ToArray();

        try
        {
            if (sqlBooking != string.Empty)
            {
                sqlStr += sqlBooking + sqlBookingDtl;
            }


            if (bookingNoteManage.BookingNoteAdd(sqlStr, parms))
            {
                if (templete != string.Empty && emailTo != string.Empty)
                {

                    string[] temps = templete.Substring(0, templete.Length - 1).Split(new char[] { '}' });
                    string[] emails = emailTo.Substring(0, emailTo.Length - 1).Split(new char[] {';'});
                    for (int i = 0; i < temps.Length; i++)
                    {
                        if (i < emails.Length)
                        {
                            string[] ems = emails[i].Split(new char[] { ',' });
                            //string subject = "reminds from special-line!";
                            //for (int j = 0; j < ems.Length; j++)
                            //{
                            //    SendMail send = new SendMail();
                            //    string content = temps[i].Replace("[title]", ems[j]);
                            //    send.MailBody = content;
                            //    send.MailSubject = subject;
                            //    send.MailTo = ems[j];

                            //    send.Send();
                            //}

                            ISyAutoSendEmail autoEmail = new SyAutoSendEmail();
                            autoEmail.InsertEmailContent("Add Shipping Order", temps[i], ems, int.Parse(Session["UserID"].ToString()));

                        }
                    }


                }

                Jscript.AlertAndRedirect(Resources.Messages.AddSuccess, "BookingNoteList.aspx", this.Page);
            }
            else
            {
                Jscript.Alert(Resources.Messages.AddFailed, this.Page);

            }


        }
        catch (Exception ee)
        {
             Jscript.Alert(Resources.Messages.AddFailed, this.Page);
            //Jscript.Alert(ee.Message.ToString());
        }

    }
    
    #endregion

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("BookingNoteList.aspx");
    }


    #region dropdwonlist的绑定和事件
    private void BindShipperLM(int clientID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ClientID", clientID.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where ClientID =@ClientID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        ddlShipperLM.DataSource = dt;
        ddlShipperLM.DataTextField = "LinkMan";
        ddlShipperLM.DataValueField = "PKID";
        ddlShipperLM.DataBind();
        ddlShipperLM.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

    }

    private void BindVendorLM(int clientID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ClientID", clientID.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where ClientID =@ClientID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        ddlVendorLM.DataSource = dt;
        ddlVendorLM.DataTextField = "LinkMan";
        ddlVendorLM.DataValueField = "PKID";
        ddlVendorLM.DataBind();
        ddlVendorLM.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

    }

    protected void ddlShipper_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlShipper.SelectedValue != "0")
        {
            ddlShipperLM.Enabled = true;

            if (ddlShipper.SelectedItem.Text == "MAT" || ddlShipper.SelectedItem.Text == "FP")
            {
                txtSourceCode.Text = "MAPS";
            }
            else
            {
                txtSourceCode.Text = string.Empty;
            }
        }
        else
        {
            txtSourceCode.Text = string.Empty;
            ddlShipperLM.Enabled = false;
        }
        ddlShipperLM.Items.Clear();
        BindShipperLM(int.Parse(ddlShipper.SelectedValue));
    }

    protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVendor.SelectedValue != "0")
        {
            ddlVendorLM.Enabled = true;
        }
        else
        {
            ddlVendorLM.Enabled = false;
        }
        ddlVendorLM.Items.Clear();
        BindVendorLM(int.Parse(ddlVendor.SelectedValue));
    }
    #endregion


    #region 修改，复制，删除缓存数据的方法
    protected void btnUpdateD_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {

            if (ViewState["BookingNote"] != null)
            {
                ClearSelect();

                DataTable dt = new DataTable();

                dt = (DataTable)ViewState["BookingNote"];

                txtConfirmNo.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["ConfirmNo"].ToString();
                ddlVendor.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VendorID"].ToString();
                ddlWhouse.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["WhouseID"].ToString();
                txtSONO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["SONO"].ToString();
                ddlFCLLCL.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["FCLLCL"].ToString();
                ddlHKPRC.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["HKPRC"].ToString();

                if (dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString() != string.Empty)
                {
                    txtJobDate.Text = Convert.ToDateTime(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString()).ToString("yyyy-MM-dd");

                    if (dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString().Substring(11,5) != "00:00")
                    {
                        txtJobDateH.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString().Substring(11, 5).Remove(2,1).Trim();
                    }
                }

                //txtDeliveryDate.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["DeliveryDate"].ToString();
                txtItemNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["ItemNO"].ToString();

                txtPCS.Text = int.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PCS"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PCS"].ToString() : string.Empty;
                txtCTN.Text = int.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["CTN"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["CTN"].ToString() : string.Empty;
                txtGrossWT.Text = float.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["GrossWT"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["GrossWT"].ToString() : string.Empty;
                txtVOL.Text = float.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VOL"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VOL"].ToString() : string.Empty;

               
                txtContainerNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["ContainerNO"].ToString();
                txtSealNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["SealNO"].ToString();
                txtVVD.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VV"].ToString();
                txtPNNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PNNO"].ToString();
                txtPCNOD.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PCNO"].ToString();
                txtCargoReadyDate.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["CargoReadyDate"].ToString();
                //txtTruckCO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["TruckCO"].ToString();
                txtRemarkD.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["Remark"].ToString();
                //txtBespokeDate.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["BespokeDate"].ToString();
               // txtSourceCode.Text =dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["SourceCode"].ToString();

                int id = 0;
                int.TryParse(ddlVendor.SelectedValue, out id);
                ddlVendorLM.Items.Clear();
                BindVendorLM(id);
                ddlVendorLM.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VendorLinkMan"].ToString() !=string.Empty ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VendorLinkMan"].ToString():"0";
                ddlVendorLM.Enabled = true;


                num = int.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["RowNum"].ToString());//给一个静态变量付值。更新哪条数据
            }

        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel2);

        }

    }
    protected void btnCopyD_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            if (ViewState["BookingNote"] != null)
            {
                ClearSelect();

                DataTable dt = new DataTable();

                dt = (DataTable)ViewState["BookingNote"];

                txtConfirmNo.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["ConfirmNo"].ToString();
                ddlVendor.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VendorID"].ToString();
                ddlWhouse.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["WhouseID"].ToString();
                txtSONO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["SONO"].ToString();
                ddlFCLLCL.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["FCLLCL"].ToString();
                ddlHKPRC.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["HKPRC"].ToString();

                if (dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString() != string.Empty)
                {
                    txtJobDate.Text = Convert.ToDateTime(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString()).ToString("yyyy-MM-dd");

                    if (dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString().Substring(11, 5) != "00:00")
                    {
                        txtJobDateH.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["JobDate"].ToString().Substring(11, 5).Remove(2, 1).Trim();
                    }
                }

                //txtDeliveryDate.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["DeliveryDate"].ToString();
                txtItemNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["ItemNO"].ToString();
                txtPCS.Text = int.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PCS"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PCS"].ToString() : string.Empty;
                txtCTN.Text = int.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["CTN"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["CTN"].ToString() : string.Empty;
                txtGrossWT.Text = float.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["GrossWT"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["GrossWT"].ToString() : string.Empty;
                txtVOL.Text = float.Parse(dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VOL"].ToString()) != 0 ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VOL"].ToString() : string.Empty;

                txtContainerNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["ContainerNO"].ToString();
                txtSealNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["SealNO"].ToString();
                txtVVD.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VV"].ToString();
                txtPNNO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PNNO"].ToString();
                txtPCNOD.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["PCNO"].ToString();
                txtCargoReadyDate.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["CargoReadyDate"].ToString();
                //txtTruckCO.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["TruckCO"].ToString();
                txtRemarkD.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["Remark"].ToString();
              //  txtBespokeDate.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["BespokeDate"].ToString();

               // txtSourceCode.Text = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["SourceCode"].ToString();

                int id = 0;
                int.TryParse(ddlVendor.SelectedValue, out id);
                ddlVendorLM.Items.Clear();
                BindVendorLM(id);
                ddlVendorLM.SelectedValue = dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VendorLinkMan"].ToString() != string.Empty ? dt.Rows[(int.Parse(Request["chkSelected"]) - 1)]["VendorLinkMan"].ToString() : "0";
                ddlVendorLM.Enabled = true;

                num = -1;
            }
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel2);
        }
    }
    protected void btnDelD_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            if (ViewState["BookingNote"] != null)
            {
                DataTable dt = (DataTable)ViewState["BookingNote"];
                dt.Rows.RemoveAt((int.Parse(Request["chkSelected"]) - 1));
                dataBind();
            }
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel2);
        }
    }
    #endregion

    protected void btnLAdd_Click(object sender, EventArgs e)
    {
        string sqlStr = @"select c.* from Sy_Client c join Sy_ClientType ct on c.PKID=ct.ClientID where 
(c.ENGName=@ENGName or c.HKName=@ENGName or c.CNName=@ENGName or  c.ENGShortName=@ENGName or c.CNShortName=@ENGName or c.HKShortName=@ENGName )
and ct.SyCodeID=7 ";

        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ENGName", txtCustomers.Text);

        DataTable dt = db.RunSqlTab(sqlStr, parms);
        if (dt != null && dt.Rows.Count > 0)
        {
            ddlCustomer.SelectedValue = dt.Rows[0]["PKID"].ToString();
        }
        else
        {
            string sql = string.Empty;
            sql = @"insert into Sy_Client(ENGName,HKName,CNName,ENGShortName,CNShortName,HKShortName,Status) 
                    values(@ENGName,@ENGName,@ENGName,@ENGName,@ENGName,@ENGName,1) SET @ReturnValue=@@Identity;
                    insert into Sy_ClientType(ClientID,SyCodeID) values(@ReturnValue,7)";
            SqlParameter[] parmsI = new SqlParameter[2];
            SqlParameter parm = new SqlParameter("@ReturnValue", 0);
            parm.SqlDbType = SqlDbType.Int;
            parm.Direction = ParameterDirection.Output;

            parmsI[0] = parm;
            parmsI[1] = new SqlParameter("@ENGName",txtCustomers.Text);
           
            db.ExecSqlTransaction(sql,parmsI);

            //客户客人
            dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.KHKR.ToString("d")));
            ddlCustomer.DataSource = dt;
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                ddlCustomer.DataTextField = "ENGShortName";
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                ddlCustomer.DataTextField = "HKShortName";
            }
            else
            {
                ddlCustomer.DataTextField = "CNShortName";
            }
            ddlCustomer.DataValueField = "PKID";
            ddlCustomer.DataBind();
            ddlCustomer.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

            ddlCustomer.SelectedIndex = ddlCustomer.Items.IndexOf(ddlCustomer.Items.FindByText(txtCustomers.Text));
        }
    }
}

